﻿using RuiXinCoffee.BLL;
using RuiXinCoffee.Model;
using RuiXinCoffee.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RuiXinCoffee.UI
{
    public partial class UserMainForm : BaseForm
    {
        private List<string> carouselImagePaths = new();
        private int currentCarouselIndex = 0;
        private CarouselImageService carouselService = new CarouselImageService();
        private System.Windows.Forms.Timer timerCarouselRefresh;

        public UserMainForm()
        {
            InitializeComponent();
            ShoppingCartService.Instance.CartUpdated += RefreshCartSummary;
            RefreshCartSummary();
            this.Load += UserMainForm_Load;
            ProductService productService = new ProductService();
            List<Product> allProducts = productService.GetAllProducts();
            LoadCarouselImages();
            timerCarousel.Start();
            //定时刷新轮播图片
            timerCarouselRefresh = new System.Windows.Forms.Timer();
            timerCarouselRefresh.Interval = 1000; //3秒刷新一次
            timerCarouselRefresh.Tick += (s, e) => LoadCarouselImages();
            timerCarouselRefresh.Start();
        }
        
        private void RefreshCartSummary()
        {
            //在状态栏显示购物车信息
            lblCartStatus.Text = $"购物车: {ShoppingCartService.Instance.getTotal()} 件商品";
            lblTotalPrice.Text = $"¥{ShoppingCartService.Instance.CalculateTotal()}";
        }
        
        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
        
        private void AddProductItem(FlowLayoutPanel flowPanel, int productId, string productName, decimal price, string categoryName, string imageUrl)
        {
            try
            {
                //商品项容器
                Panel productPanel = new Panel
                {
                    Size = new Size(140, 140),
                    Margin = new Padding(12),
                    BackColor = ColorTranslator.FromHtml("#D7E4F2"),
                    BorderStyle = BorderStyle.FixedSingle
                };

                //商品图片
                PictureBox picProduct = new PictureBox
                {
                    SizeMode = PictureBoxSizeMode.Zoom,
                    Dock = DockStyle.Top,
                    Height = 100,
                    Image = ImageHelper.LoadImage(imageUrl)
                };
                picProduct.SizeMode = PictureBoxSizeMode.Zoom;

                //商品名称
                Label lblName = new Label
                {
                    Text = productName,
                    Dock = DockStyle.Top,
                    Font = new Font("幼圆", 8),
                    TextAlign = ContentAlignment.MiddleCenter,
                    Height = 25
                };

                //价格
                Label lblPrice = new Label
                {
                    Text = $"￥{price:0.00}",
                    Dock = DockStyle.Bottom,
                    Font = new Font("幼圆", 9, FontStyle.Bold),
                    ForeColor = ColorTranslator.FromHtml("#6E3B00"),
                    Height = 15,
                    TextAlign = ContentAlignment.MiddleCenter
                };

                productPanel.Controls.Add(lblPrice);
                productPanel.Controls.Add(lblName);
                productPanel.Controls.Add(picProduct);

                flowPanel.Controls.Add(productPanel);
                picProduct.Click += (s, e) =>
                {
                    ProductDetailFrom detailForm = new ProductDetailFrom(productId, categoryName);
                    detailForm.ShowDialogWithBinding(this);
                };
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException($"添加商品项 {productName} 失败", ex));
            }
        }
        
        private void LoadCategory(string categoryName, int categoryId)
        {
            ProductService productService = new ProductService();
            List<Product> allProducts = productService.GetProductsByCategory(categoryId);

            Panel categoryPanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 200,
                Width = 2000,
                AutoSize = false
            };

            //类别标题
            Label lblCategory = new Label
            {
                Text = categoryName,
                Font = new Font("幼圆", 10, FontStyle.Bold),
                Dock = DockStyle.Top,
                Height = 30,
                ForeColor = Color.Black
            };

            FlowLayoutPanel flowPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.LeftToRight,
                WrapContents = false,
                AutoScroll = true,
                Padding = new Padding(20, 2, 20, 2)
            };

            foreach (Product product in allProducts)
            {
                AddProductItem(flowPanel, int.Parse($"{product.Id}"), $"名称: {product.Name}", decimal.Parse($"{product.Price}"), categoryName, product.ImageUrl);
            }

            categoryPanel.Controls.Add(flowPanel);
            categoryPanel.Controls.Add(lblCategory);

            UserMainFormRight.Controls.Add(categoryPanel);
        }
        
        private void UserMainForm_Load(object sender, EventArgs e)
        {
            try
            {
                ProductService productService = new ProductService();
                DataTable allCategories = productService.GetAllCategories();
                foreach (DataRow row in allCategories.Rows)
                {
                    LoadCategory(row["CategoryName"].ToString(), Convert.ToInt32(row["CategoryId"]));
                }
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("加载分类列表失败", ex));
            }
        }

        private void panelRightContent_Paint(object sender, PaintEventArgs e)
        {

        }

        private void panelRightContent_Paint_1(object sender, PaintEventArgs e)
        {

        }
        
        private void panelRightContent_Paint_2(object sender, PaintEventArgs e)
        {

        }

        private void btnMenu_Click(object sender, EventArgs e)
        {
            flowLayoutProducts.Controls.Clear();
        }

        private void btnCart_Click(object sender, EventArgs e)
        {
            CartForm cartForm = new CartForm();
            cartForm.ShowWithBinding(this);
        }

        private void pictureBoxAvatar_Click(object sender, EventArgs e)
        {

        }
        
        private void LoadCarouselImages()
        {
            try
            {
                carouselImagePaths = carouselService.GetAllImages();
                if (currentCarouselIndex >=carouselImagePaths.Count) {currentCarouselIndex = 0;}
                ShowCurrentCarouselImage();
                pictureBoxCarousel.Invalidate();
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("加载轮播图失败", ex));
            }
        }

        private void ShowCurrentCarouselImage()
        {
            try
            {
                if (carouselImagePaths.Count > 0)
                {
                    pictureBoxCarousel.Image?.Dispose();
                    pictureBoxCarousel.Image = ImageHelper.LoadCarouselImage(carouselImagePaths[currentCarouselIndex]);
                }
                else
                {
                    //没有图片时显示提示文字
                    pictureBoxCarousel.Image?.Dispose();
                    pictureBoxCarousel.Image = null;
                }
                pictureBoxCarousel.Invalidate();
            }
            catch (Exception ex)
            {
                HandleException(new ImageProcessException("显示轮播图失败", ex));
            }
        }

        private void timerCarousel_Tick(object sender, EventArgs e)
        {
            if (carouselImagePaths.Count == 0) return;
            currentCarouselIndex = (currentCarouselIndex + 1) % carouselImagePaths.Count;
            ShowCurrentCarouselImage();
        }

        private void buttonPrev_Click(object sender, EventArgs e)
        {
            if (carouselImagePaths.Count == 0) return;
            currentCarouselIndex = (currentCarouselIndex - 1 + carouselImagePaths.Count) % carouselImagePaths.Count;
            ShowCurrentCarouselImage();
        }

        private void buttonNext_Click(object sender, EventArgs e)
        {
            if (carouselImagePaths.Count == 0) return;
            currentCarouselIndex = (currentCarouselIndex + 1) % carouselImagePaths.Count;
            ShowCurrentCarouselImage();
        }

        //在图片下方绘制圆点指示器和无图片提示
        private void pictureBoxCarousel_Paint(object sender, PaintEventArgs e)
        {
            int count = carouselImagePaths.Count;
            if (count == 0)
            {
                string text = "暂无推荐图片";
                using (Font font = new Font("微软雅黑", 16, FontStyle.Bold))
                using (Brush brush = new SolidBrush(Color.LightGray))
                {
                    SizeF textSize = e.Graphics.MeasureString(text, font);
                    float x = (pictureBoxCarousel.Width - textSize.Width) / 2;
                    float y = (pictureBoxCarousel.Height - textSize.Height) / 2;
                    e.Graphics.DrawString(text, font, brush, x, y);
                }
                return;
            }

            //绘制圆点指示器
            int dotSize = 12;
            int spacing = 18;
            int totalWidth = count * dotSize + (count - 1) * spacing;
            int startX = (pictureBoxCarousel.Width - totalWidth) / 2;
            int yDot = pictureBoxCarousel.Height - dotSize - 10;
            for (int i = 0; i < count; i++)
            {
                Rectangle rect = new Rectangle(startX + i * (dotSize + spacing), yDot, dotSize, dotSize);
                e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                using (Brush brush = new SolidBrush(i == currentCarouselIndex ? Color.DodgerBlue : Color.LightGray))
                {
                    e.Graphics.FillEllipse(brush, rect);
                }
            }
        }
    }
}
